﻿using lwzlz.Application.System;
using lwzlz.Application.System.Dto;
using lwzlz.Common;
using lwzlz.Core;
using lwzlz.Web.Areas.SysAdmin.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace lwzlz.Web.Areas.SysAdmin.Controllers
{
    public class UserController : AdminController
    {
        #region 首页
        public ActionResult Index(int Id = 0)
        {
            UserService service = new UserService();
            var model = new UserOutput();
            if (Id > 0)
            {
                model = service.Get<UserOutput>(Id);
            }
            return View(model);
        }
        #endregion

        #region 获得用户了列表
        [HttpPost]
        public JsonResult GetUserList()
        {
            UserService service = new UserService();
            LayTableModel result = new LayTableModel();//layui表格返回数据格式
            try
            {
                int page = Convert.ToInt32(Request.Params["page"]);
                int limit = Convert.ToInt32(Request.Params["limit"]);

                #region 参数

                //参数
                string RealName = Request.Params["RealName"];
                string RoleName = Request.Params["RoleName"];

                string sql = @"
                    SELECT
                        *
                    FROM
                        (
                            SELECT
                                    t1.*,
                                    STUFF(
                                        (
                                            SELECT
                                                    ',' + d.RoleName
                                            FROM
                                                    [Sys_User]      b
                                                LEFT JOIN
                                                    Sys_UserRole c
                                                        ON b.Id = c.UserID
                                                LEFT JOIN
                                                    Sys_Role        d
                                                        ON d.Id = c.RoleID
                                            WHERE
                                                    b.Id = t1.Id
                                            FOR XML PATH('')
                                        ), 1, 1, ''
                                         ) RoleName
                            FROM
                                    [Sys_User]               t1
                        ) t";
                string where = " WHERE t.IsDeleted = 0 ";

                //数据库参数
                Dictionary<string, object> param = new Dictionary<string, object>();

                //状态
                if (!string.IsNullOrWhiteSpace(RealName))
                {
                    param.Add("@RealName", RealName);
                    where += " AND RealName like '%'+@RealName+'%' ";
                }
                if (!string.IsNullOrWhiteSpace(RoleName))
                {
                    param.Add("@RoleName", RoleName);
                    where += " AND RoleName like '%'+@RoleName+'%' ";
                }
                #endregion

                //排序sql语句拼接
                string orderby = " Id DESC ";
                sql += where;

                var list = service.GetDynamicPaged(page, limit, orderby, sql, param);
                var count = service.RecordQueryCount(sql, param);


                result.data = list;
                result.count = count;
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg = ex.Message;
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }
        #endregion

        #region 添加修改页面
        public ActionResult AddOrEditView(int Id = 0, int tag = 0)
        {
            ViewBag.tag = tag;
            var model = new UserOutput();
            UserService service = new UserService();
            if (Id > 0)
            {
                model = service.Get<UserOutput>(Id);
            }
            return View(model);
        }
        #endregion

        #region 添加和修改行为
        [HttpPost]
        public JsonResult AddOrEdit(UserInput model)
        {
            ResponseModel response = new ResponseModel();
            UserService service = new UserService();
            response.Success = false;
            int? count = 0;
            try
            {
                if (model.Id > 0)
                {
                    count = service.Eidt(model);
                }
                else
                {
                    count = service.Add(model);
                }
                response.Success = true;
                response.Message = "操作成功";
            }
            catch (Exception ee)
            {
                response.Success = false;
                response.Message = "失败：" + ee.Message.ToString();
            }
            return Json(response, JsonRequestBehavior.DenyGet);
        }
        #endregion

        #region 删除
        [HttpPost]
        public JsonResult DeleteList(string IdList = "")
        {
            ResponseModel response = new ResponseModel();
            UserService serviece = new UserService();
            try
            {
                serviece.DeleteList(IdList);
                response.Success = true;
                response.Message = "删除成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response, JsonRequestBehavior.DenyGet);
        }
        #endregion

        #region 重置密码
        [HttpPost]
        public JsonResult ResetPassword(int Id)
        {
            UserService service = new UserService();
            ResponseModel response = new ResponseModel();
            response.Success = false;
            string pwd = new UserService().CreateRandomPwd();
            User model = service.Get(Id);
            model.UserPWD = new Symmetric().Encrypto(pwd);
            model.LastModificationTime = DateTime.Now;
            model.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
            int count = service.UpDataSave(model);
            if (count > 0)
            {
                response.Success = true;
                response.Message = "重置成功，您的新密码为：" + pwd;
            }
            else
            {
                response.Success = false;
                response.Message = "重置失败";
            }
            return Json(response);
        }
        #endregion

        #region 设置用户角色页面
        public ActionResult SetUserRole(int Id)
        {
            ViewBag.UserId = Id;
            ViewBag.AllRoleList = new UserRoleTBService().GetRoleList(Id);
            return View();
        }
        #endregion

        #region 设置用户角色函数
        [HttpPost]
        public JsonResult SetUserRole(int Id, int roleId, bool check)
        {
            ResponseModel response = new ResponseModel();
            UserRoleTBService service = new UserRoleTBService();
            UserRole model = null;
            try
            {
                int? count = 0;
                if (check)
                {
                    model = new UserRole();
                    model.UserId = Id;
                    model.RoleId = roleId;
                    count = service.Add(model);
                }
                else
                {
                    model = service.GetRole(Id, roleId);
                    count = service.Delete(model);
                }
                if (count > 0)
                {
                    response.Success = true;
                    response.Message = "操作成功";
                }
                else
                {
                    response.Success = false;
                    response.Message = "操作失败";
                }

            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }
        #endregion

        #region 密码修改页面
        public ActionResult ChangePwdView()
        {
            UserChangePwdOut model = new UserChangePwdOut();
            return View(model);
        }
        #endregion

        #region 密码修改行为
        [HttpPost]
        public JsonResult EditPass(UserChangePwdInput model)
        {
            ResponseModel response = new ResponseModel();
            int Id = UserAuthentication.GetCurrentUser().UserID;//获取当前登录用户Id
            var User = new UserService().Get(Id);//实体
            try
            {
                string password = new Symmetric().Encrypto(model.OldPWD);
                if (password == User.UserPWD)
                {
                    //response.Message = "原来密码正确";
                    int id = new UserService().EditPWD(model);
                    response.Success = true;
                    response.Message = "修改成功，下次更改密码需要重新登录哦";
                }
                else
                {
                    response.Message = "原来密码不正确";
                    return Json(response, JsonRequestBehavior.DenyGet);
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response, JsonRequestBehavior.DenyGet);
        }
        #endregion

        #region 解锁锁定
        public JsonResult Lock(string IdList = "")
        {
            ResponseModel response = new ResponseModel();
            UserService service = new UserService();
            try
            {

                service.LockList(IdList);
                response.Success = true;
                response.Message = "解锁成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response, JsonRequestBehavior.DenyGet);
        }
        #endregion
    }
}